package at.fhj.antesk.steamvaluecalc.utils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.fhj.antesk.steamvaluecalc.Game;

public class HelperUtil {

	private static Logger logger = LoggerFactory.getLogger(HelperUtil.class);

	public static double round(double value, int places) {
		if (places < 0)
			throw new IllegalArgumentException();

		long factor = (long) Math.pow(10, places);
		value = value * factor;
		long tmp = Math.round(value);
		return (double) tmp / factor;
	}

	public static double calculateHourValueForGame(double price, double hours) {
		double hourValue = 0;

		if (hours == 0) {
			hourValue = price;
		} else {
			hourValue = price / hours;

			if (hourValue > price) {
				hourValue = price;
			}
		}
		return hourValue;
	}

	public static double sumUpHoursFromGameList(List<Game> gameList) {
		double totalHours = 0.0;

		for (Game game : gameList) {
			totalHours += game.getHoursOnRecord();
		}

		return totalHours;
	}

	public static double sumUpPricesFromGameList(List<Game> gameList) {
		double totalPrice = 0.0;

		for (Game game : gameList) {
			if (game.getPrice() != null && game.getPrice() >= 0) {
				totalPrice += game.getPrice();
			}
		}

		return totalPrice;
	}

	public static String createBoldHtmlText(String text) {
		return "<html><b>" + text + "</b></html>";
	}

	public static String formatDoubleToCurrency(double price, String currency) {
		return HelperUtil.round(price, 2) + " " + currency;
	}

	public static String[] splitAndExtractPriceAndCurrency(String data) {
		String[] result = new String[2];

		if (data.contains("\u20AC")) {
			result[0] = data.split("\u20AC")[0].replace(",", ".");
			result[1] = "\u20AC";
		} else if (data.contains("\u0024")) {
			result[0] = data.split("\\u0024")[1]; // $ must be escaped twice, since it is a regex
			result[1] = "\u0024";
		}

		return result;
	}

	public static int getRowCount(ResultSet set) {
		int counter = 0;
		try {
			while (set.next()) {
				counter++;
			}
		} catch (SQLException e) {
			logger.debug("Error occured while counting rows from ResultSet", e);
		}

		return counter;
	}
}
